import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useAuthStore } from '@/stores/auth'
import * as authApi from '@/api/auth'
import type { LoginParams } from '@/types/auth'

export function useAuth() {
  const authStore = useAuthStore()
  const router = useRouter()
  const loading = ref(false)
  
  /**
   * 登录
   * @param loginParams 登录参数
   */
  const login = async (loginParams: LoginParams) => {
    loading.value = true
    try {
      const result = await authApi.login(loginParams)
      
      // 保存登录信息
      authStore.setToken(result.accessToken)
      authStore.setRefreshToken(result.refreshToken)
      authStore.setUserInfo(result.userInfo)
      
      // 获取用户详细信息（权限等）
      await getUserInfo()
      
      message.success('登录成功')
      
      // 跳转到首页或指定页面
      const redirect = router.currentRoute.value.query?.redirect as string
      router.push(redirect || '/')
    } catch (error) {
      console.error('登录失败:', error)
      message.error('登录失败')
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 获取用户信息
   */
  const getUserInfo = async () => {
    try {
      const userInfo = await authApi.getInfo()
      authStore.setUserDetail(userInfo)
      return userInfo
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }
  
  /**
   * 登出
   */
  const logout = async () => {
    loading.value = true
    try {
      await authApi.logout()
      authStore.clearAuth()
      router.push('/login')
      message.success('已退出登录')
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  return {
    login,
    logout,
    getUserInfo,
    loading,
    isLoggedIn: authStore.isLoggedIn,
    userInfo: authStore.userInfo,
    permissions: authStore.permissions,
    roles: authStore.roles,
    isAdmin: authStore.isAdmin
  }
}
